package com.yunshan.wechat.service.impl;

import com.yunshan.common.utils.*;
import com.yunshan.member.domain.MemberSubCardInfo;
import com.yunshan.member.domain.MemberUserInfo;
import com.yunshan.member.service.IMemberSubCardInfoService;
import com.yunshan.member.service.IMemberUserInfoService;
import com.yunshan.wechat.domain.UserInfoVo;
import com.yunshan.wechat.domain.WechatUserInfo;
import com.yunshan.wechat.mapper.WechatUserInfoMapper;
import com.yunshan.wechat.service.IWechatUserInfoService;
import com.yunshan.welfare.domain.WelfareCouponRecord;
import com.yunshan.welfare.service.IWelfareCouponRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 小程序用户信息Service业务层处理
 *
 * @author yunshan
 * @date 2025-02-07
 */
@Service
public class WechatUserInfoServiceImpl implements IWechatUserInfoService
{
    @Autowired
    private WechatUserInfoMapper wechatUserInfoMapper;
    @Autowired
    private IMemberUserInfoService memberUserInfoService;
    @Autowired
    private IMemberSubCardInfoService memberSubCardInfoService;
    @Autowired
    private IWelfareCouponRecordService welfareCouponRecordService;

    /**
     * 查询小程序用户信息
     *
     * @param id 小程序用户信息主键
     * @return 小程序用户信息
     */
    @Override
    public WechatUserInfo selectWechatUserInfoById(Long id)
    {
        return wechatUserInfoMapper.selectWechatUserInfoById(id);
    }

    /**
     * 查询小程序用户信息列表
     *
     * @param wechatUserInfo 小程序用户信息
     * @return 小程序用户信息
     */
    @Override
    public List<WechatUserInfo> selectWechatUserInfoList(WechatUserInfo wechatUserInfo)
    {
        return wechatUserInfoMapper.selectWechatUserInfoList(wechatUserInfo);
    }

    /**
     * 新增小程序用户信息
     *
     * @param wechatUserInfo 小程序用户信息
     * @return 结果
     */
    @Override
    public int insertWechatUserInfo(WechatUserInfo wechatUserInfo)
    {
        //查询是否副卡会员
        MemberSubCardInfo memberSubCardInfo = memberSubCardInfoService.selectUserInfoByLoginPhone(wechatUserInfo.getLoginPhone());
        if (memberSubCardInfo != null && memberSubCardInfo.getStatus() != 3){
            wechatUserInfo.setType(2);
        }
        wechatUserInfo.setCreateTime(DateUtils.getNowDate());
        return wechatUserInfoMapper.insertWechatUserInfo(wechatUserInfo);
    }

    /**
     * 修改小程序用户信息
     *
     * @param wechatUserInfo 小程序用户信息
     * @return 结果
     */
    @Override
    public int updateWechatUserInfo(WechatUserInfo wechatUserInfo)
    {
        wechatUserInfo.setUpdateTime(DateUtils.getNowDate());
        return wechatUserInfoMapper.updateWechatUserInfo(wechatUserInfo);
    }

    /**
     * 批量删除小程序用户信息
     *
     * @param ids 需要删除的小程序用户信息主键
     * @return 结果
     */
    @Override
    public int deleteWechatUserInfoByIds(Long[] ids)
    {
        return wechatUserInfoMapper.deleteWechatUserInfoByIds(ids);
    }

    /**
     * 删除小程序用户信息信息
     *
     * @param id 小程序用户信息主键
     * @return 结果
     */
    @Override
    public int deleteWechatUserInfoById(Long id)
    {
        return wechatUserInfoMapper.deleteWechatUserInfoById(id);
    }

    @Override
    public WechatUserInfo selectWechatUserInfo(String openid, String unionid, String phone) {
        //查询是否存在小程序用户
        WechatUserInfo wechatUserInfo = wechatUserInfoMapper.selectWechatUserInfoByOpenid(openid);

        //查询是否存在会员
        MemberUserInfo memberUserInfo = memberUserInfoService.selectMemberUserInfoByLoginPhone(phone);
        if (wechatUserInfo == null){
            WechatUserInfo byLoginPhone = wechatUserInfoMapper.selectWechatUserInfoByLoginPhone(phone);
            if (byLoginPhone != null){
                throw new RuntimeException("该手机号已绑定了其他微信号");
            }

            wechatUserInfo = new WechatUserInfo();
            wechatUserInfo.setOpenId(openid);
            wechatUserInfo.setUnionId(unionid);
            wechatUserInfo.setLoginPhone(phone);
            if (memberUserInfo != null && StringUtils.isNotEmpty(memberUserInfo.getName())){
                wechatUserInfo.setName(memberUserInfo.getName());
            }else {
                //查询有没有副卡，没有则为临时会籍
                MemberSubCardInfo memberSubCardInfo = memberSubCardInfoService.selectUserInfoByLoginPhone(phone);
                if (memberSubCardInfo == null) {
                    wechatUserInfo.setName("云山用户" + StringUtil.encryptPhoneNumber(phone));
                }else {
                    wechatUserInfo.setName(memberSubCardInfo.getName());
                }
            }
            wechatUserInfo.setPhone(phone);
            insertWechatUserInfo(wechatUserInfo);
            wechatUserInfo = wechatUserInfoMapper.selectWechatUserInfoByOpenid(openid);
        }else {
            if (!wechatUserInfo.getLoginPhone().equals(phone)){
                throw new RuntimeException("该微信号已绑定了其他手机号");
            }

            WechatUserInfo byLoginPhone = wechatUserInfoMapper.selectWechatUserInfoByLoginPhone(phone);
            if (byLoginPhone != null && !byLoginPhone.getOpenId().equals(wechatUserInfo.getOpenId())){
                throw new RuntimeException("该手机号已绑定了其他微信号");
            }
        }

        //如果是主卡会员
        if (wechatUserInfo.getType() == 1) {
            if (memberUserInfo == null){
                //如果不存在，新增临时会籍会员
                memberUserInfo = new MemberUserInfo();
                memberUserInfo.setPhone(wechatUserInfo.getPhone());
                memberUserInfo.setLoginPhone(wechatUserInfo.getLoginPhone());
                memberUserInfo.setName(wechatUserInfo.getName());
                memberUserInfo.setMemberType("4");
                memberUserInfoService.insertMemberUserInfo(memberUserInfo);
            }else if(memberUserInfo.getUserId() == null){
                //更新会员信息
                memberUserInfo.setUserId(wechatUserInfo.getId());
                memberUserInfoService.updateMemberUserInfo(memberUserInfo);
            }

        } else {
            //查询是否存在副卡会员
            MemberSubCardInfo memberSubCardInfo = memberSubCardInfoService.selectUserInfoByLoginPhone(wechatUserInfo.getLoginPhone());
            if (memberSubCardInfo != null && memberSubCardInfo.getUserId() == null && memberSubCardInfo.getStatus() != 3) {
                //更新副卡会员信息
                memberSubCardInfo.setUserId(wechatUserInfo.getId());
                memberSubCardInfoService.updateMemberSubCardInfo(memberSubCardInfo);
            }
        }

        return wechatUserInfo;
    }

    @Override
    public WechatUserInfo selectWechatUserInfoByOpenid(String openId) {
        return wechatUserInfoMapper.selectWechatUserInfoByOpenid(openId);
    }

    @Override
    public UserInfoVo selectUserInfoById(Long userId) {

        UserInfoVo userInfoVo = memberUserInfoService.selectUniUserInfo(userId);

        //如果是副卡
        if (userInfoVo == null){
            userInfoVo = memberSubCardInfoService.selectUniUserInfo(userId);
            MemberUserInfo memberUserInfo = memberUserInfoService.selectMemberUserInfoById(userInfoVo.getMemberId());
            userInfoVo.setBalance(memberUserInfo.getBalance());

        //是否有副卡历史记录
        }else {
            MemberSubCardInfo memberSubCardInfo = new MemberSubCardInfo();
            memberSubCardInfo.setMemberId(userInfoVo.getMemberId());
            List<MemberSubCardInfo> memberSubCardInfos = memberSubCardInfoService.selectMemberSubCardInfoRecords(memberSubCardInfo);
            userInfoVo.setSubType(memberSubCardInfos.size());
        }

        WelfareCouponRecord welfareCouponRecord = new WelfareCouponRecord();
        welfareCouponRecord.setMemberId(userInfoVo.getMemberId());
        welfareCouponRecord.setStatus(0);

        userInfoVo.setMemberCoupon(welfareCouponRecordService.selectWelfareCouponRecordQuery(welfareCouponRecord).size());
        return userInfoVo;
    }

      @Override
    public int updateUniUserInfo(UserInfoVo userInfoVo) {
        WechatUserInfo wechatUserInfo = wechatUserInfoMapper.selectWechatUserInfoById(UserUtils.getUserId());
        if (wechatUserInfo == null){
            throw new RuntimeException("获取用户信息失败");
        }

        //如果是主卡更新主卡信息
        if(wechatUserInfo.getType() == 1){
            MemberUserInfo memberUserInfo = memberUserInfoService.selectUserInfoByUserId(wechatUserInfo.getId());
            if (memberUserInfo != null) {
                MemberUserInfo memberUser = new MemberUserInfo();
                memberUser.setId(memberUserInfo.getId());
                if (StringUtils.isNotEmpty(userInfoVo.getPhone())) {
                    memberUser.setPhone(userInfoVo.getPhone());
                    wechatUserInfo.setPhone(userInfoVo.getPhone());
                }
                if (StringUtils.isNotEmpty(userInfoVo.getRoomNumber())) {
                    memberUser.setRoomNumber(userInfoVo.getRoomNumber());
                }
                if (StringUtils.isNotEmpty(userInfoVo.getCompanyName())) {
                    memberUser.setCompanyName(userInfoVo.getCompanyName());
                }
                if (StringUtils.isNotEmpty(userInfoVo.getName())) {
                    memberUser.setName(userInfoVo.getName());
                    wechatUserInfo.setName(userInfoVo.getName());
                }
                memberUserInfoService.updateMemberUserInfo(memberUser);
            }

        //如果是副卡更新副卡信息
        }else {
            MemberSubCardInfo memberSubCardInfo = memberSubCardInfoService.selectUserInfoByUserId(wechatUserInfo.getId());
            if (memberSubCardInfo != null && StringUtils.isNotEmpty(userInfoVo.getPhone())){
                MemberSubCardInfo memberSub = new MemberSubCardInfo();
                memberSub.setId(wechatUserInfo.getId());
                if (StringUtils.isNotEmpty(userInfoVo.getPhone())) {
                    memberSub.setPhone(userInfoVo.getPhone());
                    wechatUserInfo.setPhone(userInfoVo.getPhone());
                }
                if (StringUtils.isNotEmpty(userInfoVo.getName())) {
                    memberSub.setName(userInfoVo.getName());
                    wechatUserInfo.setName(userInfoVo.getName());
                }
                memberSubCardInfoService.updateMemberSubCardInfo(memberSub);
            }

        }
        //更新微信用户信息
        if (userInfoVo.getSex() != null) {
            wechatUserInfo.setSex(userInfoVo.getSex());
        }
        if (StringUtils.isNotEmpty(userInfoVo.getAvatarUrl())) {
            wechatUserInfo.setAvatarUrl(userInfoVo.getAvatarUrl());
        }
        if (userInfoVo.getBirthday() != null) {
            wechatUserInfo.setBirthday(userInfoVo.getBirthday());
        }
        return wechatUserInfoMapper.updateWechatUserInfo(wechatUserInfo);
    }

    @Override
    public Long selectMemberIdByUserId(Long userId) {
        WechatUserInfo wechatUserInfo = wechatUserInfoMapper.selectWechatUserInfoById(userId);
        if (wechatUserInfo.getType() == 1) {
            return memberUserInfoService.selectUserInfoByUserId(wechatUserInfo.getId()).getId();
        } else {
            return memberSubCardInfoService.selectUserInfoByUserId(wechatUserInfo.getId()).getId();
        }

    }

    @Override
    public WechatUserInfo selectUserInfoByLoginPhone(String loginPhone) {
        return wechatUserInfoMapper.selectWechatUserInfoByLoginPhone(loginPhone);
    }
}
